<?php

class stFacebookToolboxFunctions extends stfunctions_2_1 {

    public function __construct($config) {
        parent::__construct($config);
    }

    public function image_zoom($file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90, $x2= 55, $y2 = 76) {
        $image = wp_load_image($file);
        if (!is_resource($image))
            return new WP_Error('error_loading_image', $image, $file);

        $size = @getimagesize($file);
        if (!$size)
            return new WP_Error('invalid_image', __('Could not read image size'), $file);
        list($orig_w, $orig_h, $orig_type) = $size;
        if ($crop) {
            $dims = array(0, 0, $x2, $y2, $max_w, $max_h, 436, 292);
        } else {
            $dims = array(0, 0, 0, 0, $max_w, $max_h, $orig_w, $orig_h);
        }

        list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;

        $newimage = wp_imagecreatetruecolor($dst_w, $dst_h);
        imagecopyresampled($newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
        // convert from full colors to index colors, like original PNG.
        if (IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor($image))
            imagetruecolortopalette($newimage, false, imagecolorstotal($image));

        // we don't need the original in memory anymore
        imagedestroy($image);

        // $suffix will be appended to the destination filename, just before the extension
        if (!$suffix)
            $suffix = "{$dst_w}x{$dst_h}";

        $info = pathinfo($file);
        $dir = $info['dirname'];
        $ext = $info['extension'];
        $name = wp_basename($file, ".$ext");

        if (!is_null($dest_path) and $_dest_path = realpath($dest_path))
            $dir = $_dest_path;
        $destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";

        if (IMAGETYPE_GIF == $orig_type) {
            if (!imagegif($newimage, $destfilename))
                return new WP_Error('resize_path_invalid', __('Resize path invalid'));
        } elseif (IMAGETYPE_PNG == $orig_type) {
            if (!imagepng($newimage, $destfilename))
                return new WP_Error('resize_path_invalid', __('Resize path invalid'));
        } else {
            // all other formats are converted to jpg
            $destfilename = "{$dir}/{$name}-{$suffix}.jpg";
            if (!imagejpeg($newimage, $destfilename, apply_filters('jpeg_quality', $jpeg_quality, 'image_resize')))
                return new WP_Error('resize_path_invalid', __('Resize path invalid'));
        }

        imagedestroy($newimage);

        // Set correct file permissions
        $stat = stat(dirname($destfilename));
        $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
        @ chmod($destfilename, $perms);

        return $destfilename;
    }

    public function appPostcardMenu($upload = true) {
        if ($upload)
            $upload_button = '<li>
                                <a onclick="toggleDiv(\'upload_field\', \'uploadObject\', \'createBucket\')" class="button add-new-h2 anchor">
                                    Upload postcard
                                </a>
                            </li>';
        $html = '
        <ul class="postcardAction float_left">
            
            <li>
                <a onclick="stFacebookToolbox.loadPage(\'dashboardPostcard\');" class="button add-new-h2 anchor">
                    Dashboard
                </a>
            </li>
            <li>
                <a onclick="stFacebookToolbox.loadPage(\'appPostcards\');" class="button add-new-h2 anchor">
                    Postcards
                </a>
            </li>
            
            <li>
                <a onclick="stFacebookToolbox.loadPage(\'appPostcardsFeatured\');" class="button add-new-h2 anchor">
                    Featured postcard
                </a>
            </li>

            <li>
                <a onclick="stFacebookToolbox.loadPage(\'appPostcardsUser\');" class="button add-new-h2 anchor">
                    User list
                </a>
            </li>
            <li>
                <a onclick="stFacebookToolbox.loadPage(\'appPostcardsCategory\');" class="button add-new-h2 anchor">
                    Categories
                </a>
            </li>
            ' . $upload_button . '
        </ul>';
        return $html;
    }

    public function setAmazonConfig($config, $smt_user_id = '') {
        if (empty($smt_user_id) && $smt_user_id != '0')
            $smt_user_id = $this->getCurrentSmtUserId($config);
        if (is_file(ABSPATH . "postcard/config/{$smt_user_id}/postcardConfig.php")) {
            require_once ABSPATH . "postcard/config/{$smt_user_id}/postcardConfig.php";
            $config['bucket_name'] = postcardConfig::AWS_S3_BUCKET_NAME;
            $config['folder_generated'] = postcardConfig::AWS_S3_GENERATED_CARD_FOLDER;
            $config['folder_template'] = postcardConfig::AWS_S3_TEMPLATE_CARD_FOLDER;
        } else {
            $config['bucket_name'] = false;
            $config['folder_generated'] = false;
            $config['folder_template'] = false;
        }
        return $config;
    }

    public function pagination2($start = NULL, $limit = NULL, $total = NULL, $cur_page = 1, $action = '') {
        if ($total > $limit) {
            $start = $start ? $start : 0;
            $limit = $limit ? $limit : $this->config['per_page'];
            $total = $total ? $total : 0;

            $total_page = ceil($total / $limit);
            $page_num = $this->config['page_num'];
            $cur_step = ceil($cur_page / $page_num);

            $max_page = ($cur_step * $page_num < $total_page) ? $cur_step * $page_num : $total_page;

            $min_page = ($cur_step - 1) * $page_num;
            $min_page = $min_page == 0 ? 1 : $min_page;

            if ($cur_page == $max_page) {
                $min_page += 1;
                $max_page = ($max_page + 1 < $total_page) ? ($max_page + 1) : $total_page;
            }

            $html = '<div id="st_pagination">';
            $html .= '<ul>';
            if ($cur_page > 1) {
                $html .= "<li><a href='javascript:void(0)' onclick='jQuery.prettyPhoto.loadPage(\"$action&cur_page=0\",null,null,function(){set_size();});' >&laquo;</a></li>";
                $html .= "<li><a href='javascript:void(0)' onclick='jQuery.prettyPhoto.loadPage(\"$action&cur_page=" . ($cur_page - 1) . "\",null,null,function(){set_size();});' >&lsaquo;</a></li>";
            }
            for ($i = $min_page; $i <= $max_page; $i++) {
                if ($i == 0 || $i == $cur_page)
                    $current = 'class="current"';
                else
                    $current = '';
                $html .= "<li $current><a href='javascript:void(0)' onclick='jQuery.prettyPhoto.loadPage(\"$action&cur_page=$i\",null,null,function(){set_size();});' >$i</a></li>";
                //{$this->config['plugin_name']}.paging($i, \"$action\")
            }
            if ($cur_page < $total_page) {
                $html .= "<li><a href='javascript:void(0)' onclick='jQuery.prettyPhoto.loadPage(\"$action&cur_page=" . ($cur_page + 1) . "\",null,null,function(){set_size();});' >&rsaquo;</a></li>";
                $html .= "<li><a href='javascript:void(0)' onclick='jQuery.prettyPhoto.loadPage(\"$action&cur_page=" . ($total_page) . "\",null,null,function(){set_size();});' >&raquo;</a></li>";
            }

            $html .= '</ul>';
            $html .= '</div>';
            return $html;
        } else {
            return;
        }
    }

    public function customEditor($content='test', $editor_id = 'content') {
        ?>
        <div id="poststuff" class="metabox-holder" style="width:650px;">
            <div id="editorcontainer">
                <div id="<?php echo $editor_id ?>">
        <?php wp_editor($content, "data[{$editor_id}]", array('dfw' => false, 'tabindex' => 1)) ?>
                </div>
            </div>
            <br class="clear" />
        </div>
        <script type="text/javascript">
            var id = '#<?php echo $editor_id ?>';
            var form = jQuery(id).parents('form').attr('id');
            form = '#'+form;
            jQuery(form).submit(function() {
                tinyMCE.triggerSave();
            });
        </script>
        <?php
    }

}
?>